package com.zgt.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zgt.dao.TopicDao;
import com.zgt.model.Research;
import com.zgt.model.Topic;
import com.zgt.service.TopicService;
import com.zgt.util.Page;

@Service("topicService")
public class TopicServiceImpl implements TopicService {

	private TopicDao topicDao;

	public TopicDao getTopicDao() {
		return topicDao;
	}

	@Resource
	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}

	public void deleteTopicById(int id) {
		topicDao.deleteTopicById(id);
	}

	public Topic getTopicById(int id) {
		return topicDao.getTopicById(id);
	}

	public Page listTopic(Page page) {
		page.setAllRow(topicDao.getCount("from Topic"));

		List topics = topicDao.listTopic(page.getOffset(), page.getPageSize());
		page.setPageResult(topics);

		return page;
	}

	public void addTopic(Topic topic) {
		topicDao.saveTopic(topic);
	}

	public void updateTopic(Topic topic) {
		topicDao.updateTopic(topic);
	}

	public void addTopics(List temList) {
		List list = new ArrayList<Topic>();
		Iterator li = temList.iterator();
		while (li.hasNext()) {
			Topic topic = new Topic();

			topic.setName((String) li.next());
			Research research = new Research();
			research.setName((String) li.next());
			topic.setResearch(research);
			topic.setRemark((String) li.next());

			if ((!topic.getName().isEmpty() && topic.getName() != null)) {
				list.add(topic);
			}

		}
		topicDao.saveTopics(list);
	}

	public Page listSearch(Page page, String key, String keyType) {
		String query = "from Topic where " + keyType + " like '%" + key + "%'";

		page.setAllRow(topicDao.getCount(query.toString()));
		List topics = topicDao.listSearch(query.toString(), page.getOffset(),
				page.getPageSize());
		page.setPageResult(topics);

		return page;
	}

}